import { Application } from 'egg';
import { DataTypes, Model } from 'sequelize';

export interface UserAttributes {
  user_id?: number;
  id?: number;
  mobile: string;
  user_name: string;
  password: string;
  role?: 'user' | 'admin';
  is_admin?: number;
  status?: number;
  avatar?: string;
  created_at?: Date;
  updated_at?: Date;
}

export interface UserInstance extends Model<UserAttributes>, UserAttributes {}

export default (app: Application) => {
  const { STRING, INTEGER, DATE } = DataTypes;

  const User = app.model.define<UserInstance>('User', {
    user_id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    mobile: {
      type: STRING(11),
      allowNull: false,
      unique: true,
      comment: '手机号',
    },
    user_name: {
      type: STRING(50),
      allowNull: false,
      comment: '用户昵称',
    },
    password: {
      type: STRING(255),
      allowNull: false,
      comment: '密码',
    },
    is_admin: {
      type: INTEGER,
      defaultValue: 0,
      comment: '是否管理员',
    },
    status: {
      type: INTEGER,
      defaultValue: 1,
      comment: '用户状态',
    },
    avatar: {
      type: STRING(255),
      comment: '用户头像',
    },
    created_at: {
      type: DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
    updated_at: {
      type: DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
  }, {
    tableName: 'users',
    comment: '用户表',
  });

  return User;
};